package fr.sedoo.metadata.shared.domain.dto;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import fr.sedoo.commons.client.util.StringUtil;
import fr.sedoo.commons.client.widget.editing.ValidationAlert;
import fr.sedoo.commons.shared.domain.AbstractDTO;
import fr.sedoo.metadata.client.message.MetadataMessage;

public class FormatDTO extends AbstractDTO {

	private String name = "";
	private String versions = "";
	private Long id;
	public static final String SEPARATOR = "@";

	public List<String> getVersions() {
		return versionsToList(versions);
	}

	public void setVersions(List<String> versions) {
		this.versions = versionsToString(versions);
	}

	public void setStringVersions(String versions) {
		this.versions = versions;
	}

	public String getStringVersions() {
		return versions;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	private String versionsToString(List<String> src) {
		StringBuilder sb = new StringBuilder();
		if (src != null) {
			Iterator<String> iterator = src.iterator();
			while (iterator.hasNext()) {
				String current = iterator.next();
				sb.append(current);
				if (iterator.hasNext()) {
					sb.append(SEPARATOR);
				}
			}
		}
		return sb.toString();
	}

	private List<String> versionsToList(String src) {
		List<String> result = new ArrayList<String>();
		if (src != null) {
			String[] split = src.split("@");
			for (int i = 0; i < split.length; i++) {
				if (split[i].trim().length() > 0) {
					result.add(split[i]);
				}
			}
		}
		return result;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	@Override
	public String getHash() {
		return getName() + "|" + getVersions();
	}

	@Override
	public List<ValidationAlert> validate() {
		List<ValidationAlert> result = new ArrayList<ValidationAlert>();
		if ((getStringVersions().trim().length() > 0) && (StringUtil.isEmpty(getName()))) {
			result.add(new ValidationAlert(MetadataMessage.INSTANCE.metadataEditingFormat(), MetadataMessage.INSTANCE.metadataEditingFormatNameIsMandatory()));
		}
		return result;
	}

}
